package com.jlsoft.config.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jlsoft.config.SimpleResponse;
import com.jlsoft.config.token.TokenConfig;
import com.jlsoft.config.web.service.AppService;
import com.jlsoft.config.web.vo.PersonUser;
import com.jlsoft.entity.User;
import com.jlsoft.service.IUserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

@RestController
@Slf4j
public class AppController {

    @Autowired
    private IUserService userService;

    @Autowired
    private AppService appService;

    @RequestMapping("/jwtme")
    @ResponseBody
    public Object currentUser (Authentication userDetails, HttpServletRequest request) throws UnsupportedEncodingException {
        String header = request.getHeader("Authorization");
        String token = header.substring("bearer ".length());

        Claims claims = Jwts.parser().setSigningKey(TokenConfig.signingKey.getBytes("UTF-8"))
                .parseClaimsJws(token).getBody();

        String company = (String) claims.get("company");

        log.debug("company:{}", company);

        return userDetails;
    }

    @RequestMapping("/person")
    @ResponseBody
    public SimpleResponse currentLoginUser(Authentication userDetails, HttpServletRequest request){

        /*List<User> userList = userService.selectList(new EntityWrapper<User>()
                .eq("user_name", "admin")
        );*/

        User user = userService.selectOne(new EntityWrapper<User>()
            .eq("user_name", "admin")
        );
        //appService.testForBaiDuApi();
        return new SimpleResponse(0, JSON.toJSONString(user), true);
    }

    @RequestMapping("/person/update")
    @ResponseBody
    public SimpleResponse updateUser (@RequestBody PersonUser personUser) {
        SimpleResponse validate = appService.validateUpdateUser(personUser);

        if(!validate.getFlag()){
            return validate;
        }

        return appService.updateUser(personUser);
    }


}
